<template>
  <section>
    <!--顶部搜索工具条-->
    <el-card :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入搜索内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item>
        <el-form-item v-if="buttonFuncs.handleAdd">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--列表-->
    <el-table
      :data="deviceList"
      v-loading="listLoading"
      style="width: 100%"
      @select="dialogCheck"
      @row-click="selectCurrentRow"
      ref="table"
      class="custom-tbl"
    >
      <el-table-column prop="Id" label="ID" width="100" sortable>
      </el-table-column>
      <el-table-column prop="GroupName" label="设备组" width="">
      </el-table-column>
      <el-table-column prop="DeviceName" label="设备名称" width="">
      </el-table-column>
      <el-table-column prop="Index" label="排序" sortable>
      </el-table-column>
      <el-table-column prop="AutoStart" label="是否启动" width="100">
        <template #default="scope">
          <el-tag
            :type="!scope.row.AutoStart ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.AutoStart ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="CgUpload" label="变化上传" width="100">
        <template #default="scope">
          <el-tag
            :type="!scope.row.CgUpload ? 'success' : 'danger'"
            disable-transitions
            >{{ !scope.row.CgUpload ? "否" : "是" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="EnforcePeriod" label="归档周期" width="100" :formatter="formatPeriod">
      </el-table-column>
      <el-table-column prop="CmdPeriod" label="指令间隔" width="100" :formatter="formatPeriod" >
      </el-table-column>
      <el-table-column prop="Description" label="描述">
        <template #default="scope">
          <span v-html="scope.row.Description.substring(0, 100)"></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="CreateTime"
        label="创建时间"
        width="250"
        sortable
      >
      </el-table-column>

      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <div v-for="item in operateButtons" v-bind:key="item.id">
            <el-button link type="primary" size="small" @click="callFunction(item, scope.row)">{{item.name}}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :page-size="6"
        :total="total"
        style="float: right"
      >
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog
      :title="dialogTitle"
      v-model="editFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-input v-model="editForm.Id" auto-complete="off" v-show="false"></el-input>
        <el-form-item label="设备组" prop="GroupId">
          <el-select v-model="editForm.GroupId" placeholder="请选择设备组">
            <el-option
              v-for="item in deviceGroupList"
              :key="item.Id"
              :label="item.GroupName"
              :value="item.Id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="DriverType">
          <el-select v-model="editForm.DriverType" placeholder="请选择设备类型">
            <el-option
              v-for="item in driverList"
              :key="item.Value"
              :label="item.ShowName"
              :value="item.Value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="DeviceName">
          <el-input v-model="editForm.DeviceName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="Index">
          <el-input v-model="editForm.Index" auto-complete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="Description">
          <el-input v-model="editForm.Description" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否启动" prop="AutoStart">
          <el-select v-model="editForm.AutoStart" placeholder="请选择">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变化上传" prop="CgUpload">
          <el-select v-model="editForm.CgUpload" placeholder="请选择">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.Name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归档周期" prop="EnforcePeriod">
          <el-input v-model="editForm.EnforcePeriod" auto-complete="off" type="number">
            <template #append>ms</template>
          </el-input>
        </el-form-item>
        <el-form-item label="指令间隔" prop="CmdPeriod">
          <el-input v-model="editForm.CmdPeriod" auto-complete="off" type="number">
            <template #append>ms</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editCancel">取消</el-button>
          <el-button
            type="primary"
            @click.native="editSubmit"
            :loading="editLoading"
            >提交</el-button
          >
        </div>
      </template>
    </el-dialog>

  </section>
</template>

<script>
import { getDeviceList, editDevice, getDeviceGroupAll, getDrivers, removeDevice } from "/@/api/device";
import { getButtonMap } from "/@/router/backEnd";
import { ElMessage} from 'element-plus'

export default {
  data() {
    return {
      operateButtons: [],
      buttonFuncs: {},
      currentRow: null,
      filters: {
        keyword: "",
      },
      dialogTitle: "编辑",
      deviceList: [],
      deviceGroupList: [],
      driverList: [],
      statusList: [
        { Name: "是", value: 1 },
        { Name: "否", value: 0 }
      ],
      total: 0,
      page: 1,
      listLoading: false,
      sels: [], //列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      editFormRules: {
        DeviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
        DriverType: [
          { required: true, message: "请选择设备类型", trigger: "blur" },
        ],
        GroupId: [
          { required: true, message: "请选择设备组", trigger: "blur" },
        ]
      },
      //编辑界面数据
      editForm: {
        Id: 0,
        Index: 0,
        DeviceName: "",
        Description: "",
        DriverType: 0,
        AutoStart: 0,
        CgUpload: 0,
        EnforcePeriod: 300,
        CmdPeriod: 300,
        GroupId: 0
      },
      
    };
  },
  methods: {
    dialogCheck(selection, row) {
      this.currentRow = null;
      this.$refs.table.clearSelection();
      if (selection.length === 0) {
        return;
      }
      if (row) {
        this.selectCurrentRow(row);
      }
    },
    selectCurrentRow(val) {
      if (val) {
        this.currentRow = val;
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(val, true);
      }
    },
    callFunction(item, row) {
      this[item.Func].call(this, row);
    },
    formatPeriod: function(row, column){
      let colData = row[column.property]
      return colData ? `${colData} ms` : "";
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    //获取用户列表
    getList() {
      let para = {
        page: this.page,
        key: this.filters.keyword,
      };
      this.listLoading = true;

      //NProgress.start();
      getDeviceList(para).then((res) => {
        this.total = res.data.dataCount;
        this.deviceList = res.data.data;
        this.listLoading = false;
        //NProgress.done();
      });
    },
    editCancel() {
      this.editFormVisible = false;
      this.editLoading = false;
      this.editForm = {Index:0};
    },
    //删除
    handleDel(row) {
      if (!row) {
        ElMessage({
          message: "请选择要删除的一行数据！",
          type: "error",
        });

        return;
      }
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { id: row.Id };
          removeDevice(para).then((res) => {
            this.listLoading = false;
            //NProgress.done();
            if (res.success) {
              ElMessage({
                message: "删除成功",
                type: "success",
              });
            } else {
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }

            this.getList();
          });
        })
        .catch(() => {});
    },
    //显示编辑界面
    handleEdit(row) {
      if (!row) {
        ElMessage({
          message: "请选择要编辑的一行数据！",
          type: "error",
        });
        return;
      }
      this.dialogTitle = "编辑"
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd() {
      this.editFormVisible = true;
      this.dialogTitle = "新增"
      this.editForm = Object.assign({})
    },
    //编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);

            editDevice(para).then((res) => {

              if (res.success) {
                this.editLoading = false;
                //NProgress.done();
                ElMessage({
                  message: res.msg,
                  type: "success",
                });
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                this.getList();
              } else {
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },
  },
  mounted() {
    this.getList();

    let buttonMap = getButtonMap(this.$route.path);
    this.buttonFuncs = buttonMap['buttonFuncs']|| [];
    this.operateButtons = buttonMap['operation'] || [];

    //初始化设备组数据
    getDeviceGroupAll().then((res) => {
        this.deviceGroupList = res.data;
        //NProgress.done();
    });

    getDrivers().then((res) => {
        this.driverList = res.data;
    });
  },
};
</script>

<style scoped>
.custom-tbl :deep() .has-gutter .el-checkbox {
  display: none;
}
</style>
